"""Replaces foreign key for case_cost and case_cost_type tables

Revision ID: 37406cca756c
Revises: da444de005a6
Create Date: 2025-03-11 16:26:52.406726

"""

from alembic import op
from sqlalchemy.engine.reflection import Inspector

# revision identifiers, used by Alembic.
revision = "37406cca756c"
down_revision = "da444de005a6"
branch_labels = None
depends_on = None


def upgrade():
    # Get the connection and inspector
    conn = op.get_bind()
    inspector = Inspector.from_engine(conn)

    # Check if the constraint exists
    constraints = inspector.get_foreign_keys("case_cost")
    constraint_names = [constraint["name"] for constraint in constraints]

    # Drop the constraint if it exists
    if "case_cost_case_cost_type_id_fkey" in constraint_names:
        op.drop_constraint("case_cost_case_cost_type_id_fkey", "case_cost", type_="foreignkey")

    # Create the new foreign key constraint
    op.create_foreign_key(
        None, "case_cost", "case_cost_type", ["case_cost_type_id"], ["id"], ondelete="CASCADE"
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, "case_cost", type_="foreignkey")
    op.create_foreign_key(
        "case_cost_case_cost_type_id_fkey",
        "case_cost",
        "case_cost_type",
        ["case_cost_type_id"],
        ["id"],
    )
    # ### end Alembic commands ###
